<?php
/**
 * AAService
 *
 * @author fusq
 */

require_once BaseUtil::getModulePath("acl") . '/models/AdminPermissionDao.php';
require_once BaseUtil::getModulePath("base") . '/services/BaseService.php';
require_once BaseUtil::getModulePath('acl') . '/constants/Permission.php';

class AAService extends BaseService{

    private $adminPermissionDao;

    private static $instance;

    private static $acl;
    
    public function __construct (){
        parent::__construct();
        $this->adminPermissionDao = new AdminPermissionDao();
        $this->adminPermissionDao->setDb($this->db);
    }
    
    public function initUserPermissions($adminId){
        $acl = new Zend_Acl();
        $role = new Zend_Acl_Role($adminId);
        $acl->addRole($role);
        $permissions = $this->adminPermissionDao->getPermissionsByAdmin($adminId);
        foreach ($permissions as $permission){
            //echo $permission['permission_key'];
            $roleResource = Permission::getResourceActionByPermission($permission['permission_key']);
            if(isset($roleResource) && !empty($roleResource)){
                if(!$acl->has($roleResource[0])){
                    $acl->add(new Zend_Acl_Resource($roleResource[0]));
                }
                $acl->allow($adminId, $roleResource[0], $roleResource[1]);
            }
        }
//        var_dump($acl->isAllowed($adminId, "admin", "index"));
//        exit();
        return $acl;
    }

    public static function isAllowed($resource , $privilege){
        $loginUser = BaseUtil::getLoginUser();
        $userId = $loginUser['uid'];
        if(self::$instance === null){
            self::$instance = new AAService();
        }   
        if(self::$acl === null){
             self::$acl = self::$instance->initUserPermissions($userId);
        }
        if(!self::$acl->has($resource)){
            return false;
        }
        return self::$acl->isAllowed($userId, $resource , $privilege);
    }


    private static $exceptResource = array(
                                            "index" => array("index"),
                                            "admin" => array("login","sublogin","logout","editinfo","subeditinfo","captcha"),
                                            "acl" => array("noaccess","getrole","index"),
                                            "agent" => array("rendercampus")
                                          );
    public static function isExcept($resource,$privilege){
        $privileges = isset(self::$exceptResource[$resource]) ? self::$exceptResource[$resource] : null;
        if(isset($privileges) && !empty($privileges)){
            return in_array($privilege, $privileges);
        }
        return false;
    }
}
